const express = require('express');
const bcrypt = require('bcrypt');
const { sign } = require('../utils/jwt');
const Result = require('../utils/Result');
const { getKnex } = require('../db/knex');

const router = express.Router();

router.post('/login', async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.json(Result.fail('用户名和密码不能为空'));
  }

  try {
    const knex = getKnex();
    const user = await knex('admin_users').where({ username }).first();

    if (!user) {
      return res.json(Result.fail('用户不存在'));
    }

    const test = await bcrypt.hash(password, 10)
    const match = await bcrypt.compare(password, user.password);
    if (!match) {
      return res.json(Result.fail('密码错误'));
    }

    const token = sign({ id: user.id, username: user.username, role: user.role });
    return res.json(Result.success({ token }));
  } catch (error) {
    console.error('登录异常', error);
    return res.json(Result.fail('登录异常'));
  }
});

module.exports = router;
